package cn.zlp.hrm.config;

import cn.zlp.hrm.handler.DefaultAccessDeniedHandler;
import cn.zlp.hrm.handler.MyAuthenticationFailureHandler;
import cn.zlp.hrm.handler.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


//    @Bean
//    public UserDetailsService userDetailsService(){
//        //提供用户信息，这里没有从数据库查询用户信息，在内存中模拟
//        InMemoryUserDetailsManager inMemoryUserDetailsManager =
//        new InMemoryUserDetailsManager();
//        inMemoryUserDetailsManager.createUser(User.withUsername("zs").password("123").authorities("admin").build());
//        return inMemoryUserDetailsManager;
//    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        // 密码编码器：不加密
        // return NoOpPasswordEncoder.getInstance();
        // 使用BCrypt加密技术,进行登录加密
        return new BCryptPasswordEncoder();
    }

    @Autowired // 注入认证成功处理器
    private MyAuthenticationSuccessHandler successHandler;

    @Autowired // 注入认证失败处理器
    private MyAuthenticationFailureHandler failureHandler;

    @Autowired // 注入授权失败异常处理器
    private DefaultAccessDeniedHandler accessDeniedHandler;

    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //登录路径放行
                // 授权配置
                .antMatchers("/login").permitAll()
                //对登录页面跳转路径放行
                .antMatchers("/login.html").permitAll()
                //============权限控制方案1：代码控制== 1 restfull支持不好，2 查询所有权限表所有的数据都要添加过来==========//
                .antMatchers("/employee/list").hasAuthority("employee:list")
                //============权限控制============//
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                             //允许表单登录
                // .successForwardUrl("/loginSuccess")             // 设置登陆成功页
                // 登录成功返回处理
                .successHandler(successHandler)
                // 登录失败返回处理
                .failureHandler(failureHandler)
                // 登录页面跳转地址
                .loginPage("/login.html")
                // 登录处理地址(必须)
                .loginProcessingUrl("/login")
                //登出路径放行 /logout
                .and().logout().permitAll()
                //关闭跨域伪造检查
                .and().csrf().disable();

        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

        // 记住我
        http.rememberMe()
                .tokenRepository(repository) // 持久,调用持久方法
                .tokenValiditySeconds(3600)	// 设置过期时间
                .userDetailsService(userDetailsService); // 用来加载用户认证信息的
    }

    @Autowired
    private PersistentTokenRepository repository;
    @Autowired
    private UserDetailsService userDetailsService;

    // 记住我功能实现配置如下：
    @Bean
    public PersistentTokenRepository repository(){
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
        repository.setDataSource(dataSource()); // 要访问数据库必须设置数据源,mybatispls不支持数据员,所有要自己设置
        // repository.setCreateTableOnStartup(true); // 自己见persistent_logins
        return  repository;
    }

    @Bean
    @Primary// 主数据源
    @ConfigurationProperties("spring.datasource1")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }
}